package com.example.qny01.controller;

import com.example.qny01.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import qny01.pojo.CommonResult;
import qny01.pojo.Student;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("Student")
@CrossOrigin
public class StudentController {

    /**
     * 从spring容器里面自动注入StudentService
     * */
    @Autowired
    private StudentService studentService;

    @Value("${server.port}")
    private String serverPort;



    /**
     * 查询全部学生
     * */
    @GetMapping("selectAll")
    public CommonResult selectAll(){
        List<Student> students =studentService.selectAll();
        return new CommonResult(200,"查询数据库成功",students);
    }

    /**
     * 根据id查询学生，传的是路径id
     * */
    @GetMapping("selectById/{id}")
    public CommonResult selectById(@PathVariable("id") Integer id){
       Student students =studentService.selectById(id);
       if(students!=null){
           return new CommonResult<Student>(200,"查询成功"+serverPort,students);
       }else{
           return new CommonResult<Student>(444,"没有查询到该用户"+serverPort,null);
       }
    }

    /**
     * restful风格，post用来添加
     * */
    @PostMapping("insert")
    public CommonResult insert(@RequestBody Student student){
        System.out.println("调用了insert方法");
        int result = studentService.insert(student);
        if(result>0){
            return new CommonResult(200,"添加数据成功"+serverPort,result);
        }else {
            return new CommonResult(444,"添加数据失败"+serverPort,null);
        }
    }

    @DeleteMapping("delete/{id}")
    public CommonResult delete(@PathVariable("id") Integer id){
        System.out.println("调用了delete方法");

        int delete = studentService.delete(id);
        if(delete>0){
            return new CommonResult(200,"删除数据成功"+serverPort,delete);
        }else {
            return new CommonResult(444,"删除数据失败"+serverPort,null);
        }
    }

    /**
     * 更新操作
     * */
    @PutMapping("update")
    public CommonResult update(@RequestBody Student student){
        System.out.println("调用了update方法");
        int result = studentService.update(student);
        if(result>0){
            return new CommonResult(200,"更新数据成功"+serverPort,result);
        }else {
            return new CommonResult(444,"更新数据失败"+serverPort,null);
        }
    }

}
